import Component from 'utils/js/jquery-component';
import createClass from 'utils/js/create-class';
import s from './index.css';
import loadImages from 'utils/js/loadImages';

export default createClass(Component, {
  __name__: 'Example',
  locals: s,

  __init__: function (el, srcs) {
    this.$wrap = this.$(el || document.body);
    this.$html = this.$(this.rh('<div class="box"></div>'));
    this.playing = false;
    this.imgIdx = -1;
    this.srcs = srcs || [];
    var me = this;
    loadImages(this.srcs).then(function (srcs) {
      var imgs = me.rh(srcs.map(function (src) {
        return `<img class="img" src="${src}">`;
      }).join(''));
      me.$imgs = me.$(imgs);
      me.$html.html(me.$imgs);
      me.$html.appendTo(me.$wrap);
      me.srcs.length && me.play();
    }).catch(function (e) {
      console.error(e);
    });
  },

  play: function () {
    if (this.playing) return;
    var me = this;
    var loop = function () {
      me.$html.toggleClass(s.big);
      me.$imgs.eq(me.imgIdx).removeClass(s.in);
      me.imgIdx = (me.imgIdx + 1) % me.srcs.length;
      me.$imgs.eq(me.imgIdx).addClass(s.in);

      me.timer = setTimeout(loop, 4000);
    };
    loop();
  },

  pause: function () {
    clearTimeout(this.timer);
    this.playing = false;
  },
});
